package com.freight.order.serviceimpl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.freight.core.common.exception.FreightException;
import com.freight.core.common.utils.SecurityUtil;
import com.freight.core.common.vo.SearchVo;
import com.freight.core.entity.User;
import com.freight.core.service.OperationLogService;
import com.freight.order.dao.MobileTrackDao;
import com.freight.order.dao.OrderExtendDao;
import com.freight.order.dto.OrderExtendDto;
import com.freight.order.entity.*;
import com.freight.order.service.*;
import com.freight.user.dao.VehicleLicenseDao;
import com.freight.user.entity.VehicleLicense;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 订单扩展信息接口实现
 *
 * @author huyingtai
 */
@Slf4j
@Service
public class OrderExtendServiceImpl implements OrderExtendService {

    @Autowired
    private OrderExtendDao orderExtendDao;

    @Autowired
    private OperationLogService operationLogService;

    @Autowired
    private OrderOrderService orderOrderService;

    @Autowired
    private VehicleLicenseDao vehicleLicenseDao;

    @Autowired
    private OrderTrackService orderTrackService;

    @Autowired
    private MobileTrackDao mobileTrackDao;


    @Autowired
    private SecurityUtil securityUtil;

    private static double EARTH_RADIUS = 6371.393;


    @Override
    public OrderExtendDao getRepository() {
        return orderExtendDao;
    }

    @Override
    public Page<OrderExtend> findByCondition(OrderExtend orderExtend, SearchVo searchVo, Pageable pageable) {

        return orderExtendDao.findAll(new Specification<OrderExtend>() {
            @Nullable
            @Override
            public Predicate toPredicate(Root<OrderExtend> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                // TODO 可添加你的其他搜索过滤条件 默认已有创建时间过滤
                Path<Date> createTimeField = root.get("createTime");
                List<Predicate> list = new ArrayList<>();
                // 创建时间
                if (StrUtil.isNotBlank(searchVo.getStartDate()) && StrUtil.isNotBlank(searchVo.getEndDate())) {
                    Date start = DateUtil.parse(searchVo.getStartDate());
                    Date end = DateUtil.parse(searchVo.getEndDate());
                    list.add(cb.between(createTimeField, start, DateUtil.endOfDay(end)));
                }
                Predicate[] arr = new Predicate[list.size()];
                cq.where(list.toArray(arr));
                return null;
            }
        }, pageable);
    }


    private static double rad(double d)
    {
        return d * Math.PI / 180.0;
    }
    @Override
    public Long saveOrderExtend(OrderExtendDto orderExtendDto) {
        // 登录认证
        User user =securityUtil.getCurrUser();

        Long orderId = orderExtendDto.getOrderId(); // 运单id
        if (orderId == null) {
            throw new FreightException("运单不存在");
        }
        OrderOrder order=orderOrderService.get(orderId);

        if(order.getOrderState()==-1){
            throw new FreightException("运单已取消");
        }
        if(order.getOrderState()!=1){
            throw new FreightException("运单已装货");
        }

        if(order.getAddressFence()!=null&&order.getAddressFence().equals("1")){
            //判断是否在允许范围内
            double radLat1 = rad(orderExtendDto.getLat());
            double radLat2 = rad(order.getBeginLat());
            double a = radLat1 - radLat2;
            double b = rad(orderExtendDto.getLng()) - rad(order.getBeginLng());
            double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
                    Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
            s = s * EARTH_RADIUS;
            s = Math.round(s * 1000);
            log.info(String.valueOf(s));
            if (s > (order.getPretendEnclosure() * 1000)){
                throw new FreightException("您还未到达指定装货地点，请到达后操作");
            }
        }

        VehicleLicense vehicleLicense = vehicleLicenseDao.getOne(order.getVehicleId());
        OrderExtend orderExtend = orderExtendDao.findByOrderId(orderId);
        orderExtend.setBeginLat(orderExtendDto.getLat());
        orderExtend.setBeginLng(orderExtendDto.getLng());
        orderExtend.setLoadingTime(new Date());
        orderExtend.setVehicleNum(vehicleLicense.getVehicleNum());
        orderExtendDao.save(orderExtend);

        order.setOrderState(2);
        order.setTransGoodWeight(order.getGoodWeight());
        orderOrderService.save(order);

        MobileTrack mobileTrack = new MobileTrack();
        mobileTrack.setLat(String.valueOf(orderExtendDto.getLat()));
        mobileTrack.setLon(String.valueOf(orderExtendDto.getLng()));
        mobileTrack.setDriverUserId(Long.valueOf(order.getDriverUserId()));
        mobileTrack.setOrderId(orderId);
        mobileTrack.setVehicleLicenseId(order.getVehicleId());
        mobileTrack.setOrderState(2);
        mobileTrack.setMobileModel(null);
        mobileTrackDao.save(mobileTrack);

        //操作记录
        operationLogService.saveOperationLog(6,"司机装货",orderExtendDto.getOrderId().toString());

        return null;

    }

    public static void main(String[] args) {
        Double approvedLoad = Double.valueOf("1");
        System.out.println(approvedLoad);
        if(approvedLoad<1.0){
            System.out.println("1");
        }else {
            System.out.println("2");
        }
    }

    @Override
    public void updateOrderExtend(OrderExtendDto orderExtendDto) {
        // 登录认证
        User user =securityUtil.getCurrUser();

        Long orderId = orderExtendDto.getOrderId();
        OrderOrder order=orderOrderService.get(orderId);

        if (orderId == null) {
            throw new FreightException("运单不存在");
        }

        if(order.getAddressFence()!=null&&order.getAddressFence().equals("1")){
            //判断是否在允许范围内
            double radLat1 = rad(orderExtendDto.getLat());
            double radLat2 = rad(order.getEndLat());
            double a = radLat1 - radLat2;
            double b = rad(orderExtendDto.getLng()) - rad(order.getEndLng());
            double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
                    Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
            s = s * EARTH_RADIUS;
            s = Math.round(s * 1000);
            log.info(String.valueOf(s));
            if (s > (order.getDischargeEnclosure() * 1000)){
                throw new FreightException("您还未到达指定卸货地点，请到达后操作");
            }
        }


        if (orderId != null) {
            OrderExtend orderExtend = orderExtendDao.findByOrderId(orderId);
            orderExtend.setEndLng(orderExtendDto.getLng());
            orderExtend.setEndLat(orderExtendDto.getLat());
            orderExtend.setDischargeTime(new Date());

            order.setOrderState(3);
            order.setRealGoodWeight(order.getTransGoodWeight());

            MobileTrack mobileTrack = new MobileTrack();
            mobileTrack.setLat(String.valueOf(orderExtendDto.getLat()));
            mobileTrack.setLon(String.valueOf(orderExtendDto.getLng()));
            mobileTrack.setDriverUserId(Long.valueOf(order.getDriverUserId()));
            mobileTrack.setOrderId(orderId);
            mobileTrack.setVehicleLicenseId(order.getVehicleId());
            mobileTrack.setOrderState(4);
            mobileTrack.setMobileModel(null);

            orderExtendDao.save(orderExtend);
            orderOrderService.save(order);
            mobileTrackDao.save(mobileTrack);

            //操作记录
            operationLogService.saveOperationLog(6,"司机卸货",orderExtendDto.getOrderId().toString());

        }
    }

}